package pri.zxx.excelgenerate.excelhanler;

import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import lombok.SneakyThrows;

public class PageHeader implements IEventHandler {


    private String pdfNumber;

    public PageHeader(String pdfNumber) {
        this.pdfNumber = pdfNumber;
    }

    @SneakyThrows
    @Override
    public void handleEvent(Event event) {
        final PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        final PdfDocument pdfDoc = docEvent.getDocument();
        final Document doc = new Document(pdfDoc);
        final PdfPage page = docEvent.getPage();
        final Rectangle pageSize = page.getPageSize();
        final float pdfWidth = pageSize.getWidth();
        final float pdfHeight = pageSize.getHeight();

        final float tableWidth = pdfWidth - doc.getRightMargin() - doc.getLeftMargin();
        // 页眉
        final Table headerTable = new Table(2);
        headerTable.setWidth(tableWidth);
        headerTable.setHorizontalAlignment(HorizontalAlignment.CENTER);


        final Paragraph number = new Paragraph();
        number.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        number.add(pdfNumber);

        final Cell txtCel = new Cell();
        txtCel.add(number);
        txtCel.setFontSize(9f);
        txtCel.setBorder(Border.NO_BORDER);
        txtCel.setTextAlignment(TextAlignment.RIGHT);
        txtCel.setHorizontalAlignment(HorizontalAlignment.RIGHT);
        headerTable.addCell(txtCel);

        headerTable.setFixedPosition(doc.getLeftMargin(), pdfHeight-50, tableWidth);
        doc.add(headerTable);
    }
}
